#include<stdio.h>
#include "main.h"
#include <string.h>

int recorddata(FILE* file, struct contact data[], int* p_index, int is_text)
{
	int j, i, ret_fw;
	if ((*p_index) < 0){
		puts("No records to be written.");
		return 1;
	} else {
		if (is_text == TRUE){
			for (i = 0; i < (*p_index); i++){
				j = 0;
				while (data[i].name[j] != '\0'){
					if (fputc(data[i].name[j], file) == EOF){
						puts("Error while writing the NAME struct to the file.");
						return 1;
					}
					j++;
				}
				fprintf(file, "\n");
				fprintf(file, "%d\n", data[i].age);
				j = 0;
				while (data[i].tel[j] != '\0'){
					if (fputc(data[i].tel[j], file) == EOF){
						puts("Error while writing the TEL struct to the file.");
						return 1;
					}
					j++;
				}
				fprintf(file, "\n");
			}
		} else {
			if (is_text == FALSE){
				ret_fw = fwrite(data, sizeof(struct contact), (*p_index), file);
				printf("Binary Records written %d\n", ret_fw);
			}
		}
	}
	printf("%d records written to the file.\n", (*p_index));
	*p_index = 0;
	return 0;
}
